<?php
defined('IN_TS') or die('Access Denied.');

class wechat extends tsApp{

    public $bot_url = 'http://127.0.0.1:8999';

    //构造函数
    public function __construct($db){

        $tsAppDb = array();
        include 'app/duty/config.php';
        //判断APP是否采用独立数据库
        if($tsAppDb){
            $db = new MySql($tsAppDb);
        }

        parent::__construct($db);
    }

    public function getAccessToken(){
        $appid="wx2ef8a11062078826";
        $secret="16863a6f1c9e1a438b5c05922681c3d3";
        $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
        $ret=$this->find('token');
        $time=time();
        if($ret){
            $tid=$ret['tid'];
            $tt=$time - $ret['ts'];
            if($tt >= 7200){
                $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
                $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
                $token=$result['access_token'];
                $this->update('token',array('tid'=>$tid),array('token'=>$token,'ts'=>$time));
            }else{
                $token=$ret['token'];
            }
        }else{
            $res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
            $result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
            $token=$result['access_token'];
            $this->create('token',array('token'=>$token,'ts'=>$time));
        }
        return $token;
    }

    public function sendwechat($type,$userid,$arr=null,$url){

        $js = intval($_GET['js']);

        $strUser = aac('user')->find('user_info', array('userid'=>$userid), 'wxopenid');
        switch($type){
            case 1:
                $data = array(
                    'first'=>array('value'=>'您有一个新的微澜社区邮件', 'color'=>'#0A0A0A'),
                    'keyword1'=>array('value'=>$arr['subject'], 'color'=>'#0A0A0A'),
                    'keyword2'=>array('value'=>'未阅读', 'color'=>'#0A0A0A'),
                    'keyword3'=>array('value'=>date('Y-m-d H:i:s',time()),'color'=>'#0A0A0A'),
                    'remark'=>array('value'=>'请点击查看。', 'color'=>'##0A0A0A')
                );

                $templateId = 'UdDb-U8X6r-QYwT96VuXIHqxAElaVMeMdjwQ6ox7CSI';
                break;
            case 2:
                $data = array(
                    'first'=>array('value'=>'您管理的志愿者提交了一个新的服务时长申请', 'color'=>'#0A0A0A'),
                    'keyword1'=>array('value'=>$arr['username'], 'color'=>'#0A0A0A'),
                    'keyword2'=>array('value'=>$arr['term'], 'color'=>'#0A0A0A'),
                    'remark'=>array('value'=>'请前往微澜社区核定。', 'color'=>'##0A0A0A')
                );

                $templateId = 'QTYmIjk8kIdeKiEWhAo7-V1VceyOd_yTKzdM1mo1lA0';
                break;
            case 3:
                $data = array(
                    'first'=>array('value'=>'您管理的小组有人申请加入', 'color'=>'#0A0A0A'),
                    'keyword1'=>array('value'=>$arr['user'], 'color'=>'#0A0A0A'),
                    'keyword2'=>array('value'=>$arr['group'], 'color'=>'#0A0A0A'),
                    'keyword3'=>array('value'=>'无', 'color'=>'#0A0A0A'),
                    'remark'=>array('value'=>'请前往微澜社区受理。', 'color'=>'##0A0A0A')
                );

                $templateId = 'OPbd-hDK6LUCuPmajjqG4FvGXfxMaDSsFRc6c3zfvy0';
                break;
            case 4:
                $data = array(
                    'first'=>array('value'=>'您的服务时长有更新', 'color'=>'#0A0A0A'),
                    'keyword1'=>array('value'=>$arr['dutyname'], 'color'=>'#0A0A0A'),
                    'keyword2'=>array('value'=>$arr['term'], 'color'=>'#0A0A0A'),
                    'keyword3'=>array('value'=>$arr['count_duty'], 'color'=>'#0A0A0A'),
                    'remark'=>array('value'=>'请查看打卡页面，你可以在朋友圈晒一下。', 'color'=>'##0A0A0A')
                );

                $templateId = 'nKluqbLhwzOC_EmyLf9aPmBDQsyhGW8DDMWXzLclreM';
                break;
            case 5:
                $data = array(
                    'first'=>array('value'=>'活动报名成功。', 'color'=>'#0A0A0A'),
                    'keyword1'=>array('value'=>$arr['title'], 'color'=>'#0A0A0A'),
                    'keyword2'=>array('value'=>date('Y-m-d H:i',$arr['begintime']), 'color'=>'#0A0A0A'),
                    'keyword3'=>array('value'=>$arr['address'], 'color'=>'#0A0A0A'),
                    'remark'=>array('value'=>'请点击查看详情。', 'color'=>'##0A0A0A')
                );

                $templateId = 'YxTXkzHQsPR0Ch7zoBUjTgQKnL3gVSrBKWGHVkCvOuY';
                break;
            case 6:
                $text='';
                switch($arr['role2']){
                    case '中级志士':
                        $honor = '志士';
                        break;
                    case '初级仁人';
                        $honor = '仁人';
                        break;
                    case '初级贤者';
                        $honor = '贤者';
                        break;
                    case '初级元勋';
                        $honor = '元勋';
                        break;
                }
                if($arr['role2']=='中级志士'||$arr['role2']=='初级仁人'||$arr['role2']=='初级贤者'||$arr['role2']=='初级元勋'){
                    $text = '你获得一枚'.$honor.'勋章，可以在升级页面点击按钮登记领取！';
                }
                $data = array(
                    'first'=>array('value'=>'您已经升为新等级。', 'color'=>'#0A0A0A'),
                    'keyword1'=>array('value'=>$arr['role1'], 'color'=>'#0A0A0A'),
                    'keyword2'=>array('value'=>$arr['role2'], 'color'=>'#0A0A0A'),
                    'keyword3'=>array('value'=>date('Y-m-d H:i:s'), 'color'=>'#0A0A0A'),
                    'remark'=>array('value'=>'请查看升级页面，你可以在朋友圈晒一下。'.$text, 'color'=>'##0A0A0A')
                );

                $templateId = 'T3BZnj99OjNNEOk-h-SHBg41atrIg-oz3pMOjfZPsI8';
                break;
            case 7:
                $data = array(
                    'first'=>array('value'=>'有新志愿者报名。', 'color'=>'#0A0A0A'),
                    'keyword1'=>array('value'=>'微澜图书馆', 'color'=>'#0A0A0A'),
                    'keyword2'=>array('value'=>$arr['group'], 'color'=>'#0A0A0A'),
                    'keyword3'=>array('value'=>$arr['username'], 'color'=>'#0A0A0A'),
                    'keyword4'=>array('value'=>date('Y-m-d H:i',time()), 'color'=>'#0A0A0A'),
                    'keyword5'=>array('value'=>'待审核', 'color'=>'#0A0A0A'),
                    'remark'=>array('value'=>'请点击查看详情。', 'color'=>'##0A0A0A')
                );

                $templateId = 'dCsqqXxp5OaL8KW_suKZBqjTfvcdUuZamOPMjLof6kQ';
                break;
            case 8:
                $data = array(
                    'first'=>array('value'=>'您的服务时长有更新', 'color'=>'#0A0A0A'),
                    'keyword1'=>array('value'=>$arr['dutyname'], 'color'=>'#0A0A0A'),
                    'keyword2'=>array('value'=>$arr['term'], 'color'=>'#0A0A0A'),
                    'keyword3'=>array('value'=>$arr['count_duty'], 'color'=>'#0A0A0A'),
                    'remark'=>array('value'=>'您在半年内累计服务满5次，获得了馆东身份，请点击查看新馆东指南。', 'color'=>'##0A0A0A')
                );

                $templateId = 'nKluqbLhwzOC_EmyLf9aPmBDQsyhGW8DDMWXzLclreM';
                break;
        }

        $Token=$this->getAccessToken();//获取token
        $queryurl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$Token;
        $template = array(
            'touser'=>$strUser['wxopenid'],
            'template_id'=>$templateId,
            'url'=>$url,
            'data'=>$data,
        );

        https_post($queryurl, json_encode($template));//发送模板消息

        return true;

    }

    /**
     * 发送消息给微澜分馆的微信群
     *
     * @param int $groupid
     * @param string $content
     * @return boolean
     */
    public function sendMsgToGroup($groupid, $content)
    {
        $url = "{$this->bot_url}/message/sendMsgToGroup";
        $data = [ "groupid" => $groupid, "content" => $content ];
        try {
            $res = json_decode(vpost($url, $data), true); 
            if ($res["code"] != 0) {
                record_error("发送消息给分馆的微信群失败：".$res["msg"]);
                return false;
            }
        } catch (\Throwable $th) {
            error_log("发送消息给分馆的微信群失败：".$th->getMessage());
            return false;
        }
        return true;
    }

    /**
     * 发送消息给指定名称的微信群
     *
     * @param string $group_name
     * @param string $content
     * @param boolean $wideCity 是否发布到同城群
     * @return boolean
     */
    public function sendMsgToRoom($group_name, $content, $wideCity = false)
    {
        if ($wideCity) {
            preg_match('/(.*?)\d.*/', $group_name, $matches);
            if (isset($matches[1])) {
                $group_name = "微澜{$matches[1]}大本营";
            }
        }
        $url = "{$this->bot_url}/message/sendMsgToRoom";
        $data = [ "group_name" => $group_name, "content" => $content ];
        try {
            $res = json_decode(vpost($url, $data), true); 
            if ($res["code"] != 0) {
                record_error("发送给微信群失败：".$res["msg"]);
                return false;
            }
        } catch (\Throwable $th) {
            record_error("发送消息给微信群失败：".$th->getMessage());
            return false;
        }
        return true;
    }
    
}
?>